package com.qf.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.qf.pojo.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@Component
public class AlipayTools {

//    private String url = "https://openapi.alipaydev.com/gateway.do";
    private String url = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private String APPID = "2021000122671728";
    private String FORMAT = "json";
    private String CHARSET = "utf-8";
    private String SIGN_TYPE = "RSA2";
    private String net = "https://7412op8659.goho.co:443/";
//    private String net = "http://6bre3w.natappfree.cc/";
    private String privateKey="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCHPwXNn+tuT1oDfrvznhlV4Yq5izuQVg8WCIyrJC2tycdt51cGTnyaAVRBVh3Nn5WKndujK5EfbN+esvueEVThjIA5AIw1MImWQOliK3qpNs0disiQIE+CluMBsrhtFuerVe8Jjhk/iWVblPcmlrJqnTdEC229FpVf8CAjVJJAVXJS2CVvOK9/9s8ZEkVpfKMCgB6OU54UU1qgjfbOwly69D9JpuN5id9QNRHHo5hvWDPMpKDo9OQ5g1KFS09/7dH/FuDiH+2Haj/1cEVObvQsX6caDOjcUGMS11hewWiRzx4iigEnYEvG7lN/UKALw8Bi0HrMjTObDWbiiqfRw78lAgMBAAECggEADfPRfHIYDqw/BAdKCorv4C1Ba3zSq0RFkCdXo7w6vigH2+22y57DOfwTHh5tOq5Q9hjs9Ltk4FISC8Q5MwhkslQVUkwdKsuUFh0iNo93uwc9R+PuZvf+W+GHD8DJR+/J/KID4/912VkqTLVkfeWkCF2puupW6t/ujxQtrJdn8xz1wlqRZO0AQ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w0BAQEFAAOCAQ8AMIIBCgKCAQEAvAghmqTkTeqCsP27NftBz1yA/cQWlWyTvn0raw+X9eGJcYdqz/X8Oc6EsMmTcvHFtMlLVlsWenYtGUSXOEVBd2AIXUr4fjuKo9I5eqXubfgt8mfQAI7Sftq2XdbC8GQIin8g6IjpIxJqJ8LoNXHxOUncN3NZP8sVLtF7CyKVQYYdAugsQSfr0XRDxXUpwI0I0wFF2/CJsFPtCrwxY/NY6Jp0sczdQ8egCWY56kPZXC7A4GSz/UChg6Yw5sEDhV4hBPC+oKc3CEmGZvwQWX4vZgP2uVNgAZotohJFdUfGUxD1uAX2TpgpyyAs9XvAy14SyiFDlGixCdr6+mIuQIhu2wIDAQAB";

    public String alipay(Order order) {
        AlipayClient alipayClient = new DefaultAlipayClient(url,APPID,privateKey,FORMAT,CHARSET,publicKey,SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl(net + "order/updateStatusAsync");
//同步跳转地址，仅支持http/https
        request.setReturnUrl(net + "order/updateStatusSync");
/******必传参数******/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", UUID.randomUUID().toString());
//支付金额，最小值0.01元
        bizContent.put("total_amount", order.getOrderValue());
//订单标题，不可使用特殊符号
        bizContent.put("subject", order.getOrderId());
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

/******可选参数******/
//bizContent.put("time_expire", "2022-08-01 22:00:00");

//// 商品明细信息，按需传入
//JSONArray goodsDetail = new JSONArray();
//JSONObject goods1 = new JSONObject();
//goods1.put("goods_id", "goodsNo1");
//goods1.put("goods_name", "子商品1");
//goods1.put("quantity", 1);
//goods1.put("price", 0.01);
//goodsDetail.add(goods1);
//bizContent.put("goods_detail", goodsDetail);

//// 扩展信息，按需传入
//JSONObject extendParams = new JSONObject();
//extendParams.put("sys_service_provider_id", "2088511833207846");
//bizContent.put("extend_params", extendParams);

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
            return response.getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
//        if(response.isSuccess()){
//            System.out.println("调用成功");
//        } else {
//            System.out.println("调用失败");
//        }
    }
    public static Map<String, String> convert(HttpServletRequest request){
        //空集合
        Map<String, String> retMap = new HashMap<String, String>();
        //将所有请求参数转为一个set集合
        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
        //遍历set
        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();//获得键值
            String[] values = entry.getValue();//获得值
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }
        return retMap;
    }
}
